<?php

namespace app\admin\controller;

use app\common\controller\Backend;

/**
 * 产品分类管理
 *
 * @icon fa fa-circle-o
 */
class Productcate extends Backend
{
    
    /**
     * Productcate模型对象
     * @var \app\admin\model\Productcate
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Productcate;

    }
    //产品分类
    public function category(){
        $keySearch = session('productcate:keywords:search');
        if(!empty($keySearch)) {
            $searchKeyword['catename'] = ['like', '%'.$keySearch .'%'];
        }else{
            $searchKeyword = [];
        }

        $productCate = model('productcate')
            -> where(['uid' => session('userinfo:id')])
            -> where($searchKeyword)
            -> order('id desc')
            -> paginate(5);
        $page = $productCate -> render();

        $this -> assign('page', $page);
        $this -> assign('productcate', $productCate);
        return view();
    }
    //增加分类
    public function addproductcate(){
        if($this -> request -> isPost()){
            $input = input('post.');
            $input['create_time'] = time();
            $input['update_time'] = time();
            $input['uid'] = session('userinfo:id');
            $result = model('productcate') -> insert($input);
            if($result){
                return json(['status' => 1, 'info' => '添加成功！']);
            }else{
                return json(['status' => 0, 'info' => '添加失败！']);
            }
        }
        return view();
    }
    //编辑分类
    public function editproductcate(){
        if($this -> request -> isPost()){
            $input = input('post.');
            $input['update_time'] = time();
            $result = model('productcate') -> where(['id' => $input['id']]) -> update($input);
            if($result) {
                return json(['status' => 1, 'info' => '更新成功！']);
            }else{
                return json(['status' => 0, 'info' => '更新失败！']);
            }
        }

        if($this -> request -> isGet()){
            $input['id'] = input('param.id');
            $result = model('productcate') -> field('id,catename') -> where(['id' => $input['id']]) -> find();
            if($result) {
                return json(['status' => 1, 'data' => $result, 'info' => '获取成功！']);
            }else{
                return json(['status' => 0, 'info' => '获取信息失败！']);
            }
        }
    }
    //删除分类
    public function delcate()
    {
        $id = input('id');
        $result = model('productcate') -> where(['id' => $id]) -> delete();
        if($result){
            echo "<script>top.location.href='/admin/productcate/category?ref=addtabs'</script>";
        }else{
            return json(['status' => 0, 'info' => '删除失败！']);
        }
    }
    //批量删除新闻分类
    public function delSelectInput(){
        $input = input('post.');
        $inputid = json_decode($input['checkList'], true);
        $ids['id'] = implode(',', $inputid);
        $delResult = model('productcate') -> where(['id' => ['in', $ids['id']]]) -> delete();
        if($delResult){
            return json(['status' => 1, 'info' => '删除成功！']);
        }
        return json(['status' => 0, 'info' => '删除失败！']);
    }
    //分类搜索页
    public function searchProductcateKeywords(){
        $search = input('post.');
        if(!empty($search['search'])){
            session('productcate:keywords:search', $search['search']);
        }else{
            session('productcate:keywords:search', null);
        }
    }

    //产品展示页
    public function productindex(){

        $keySearch = session('products:keywords:search');
        if(!empty($keySearch)) {
            $searchKeyword['title'] = ['like', '%'.$keySearch .'%'];
            $searchKeyword['keywords'] = ['like', '%'.$keySearch .'%'];
            $searchKeyword['detail'] = ['like', '%'.$keySearch .'%'];
        }else{
            $searchKeyword = [];
        }

        $productList = model('product')
            -> where(['uid' => session('userinfo:id')])
            ->where(function ($q) use($searchKeyword) {
                $q->whereOr($searchKeyword);
            })
            -> order('id desc')
            -> paginate(5);
        $page = $productList -> render();

        foreach ($productList as &$val){
            $val['create_time'] = date('Y-m-d H:i:s', $val['create_time']);
        }

        $this -> assign('page', $page);
        $this -> assign('productList', $productList);
        return view();
    }
    //搜索产品
    public function searchProductsKeywords(){
        $search = input('post.');
        if(!empty($search['search'])){
            session('products:keywords:search', $search['search']);
        }else{
            session('products:keywords:search', null);
        }
    }
    //添加产品
    public function addproduct(){

        if($this -> request -> isPost()){
            $input = input('post.');
            // 过滤javascript与CSS
            $input['content'] = preg_replace('/<script[^>]*?>.*?<\/script>/si','',$input['content']);
            $input['content'] = htmlspecialchars_decode($input['content']);
            $input['content'] = preg_replace("/<a[^>]*>(.*?)<.*?\/a.*?>/is", "$1", $input['content']);
            $input['create_time'] = time();
            $input['uid'] = session('userinfo:id');
            $result = model('product') -> insert($input);
            if($result){
                return json(['status' => 1, 'info' => '添加成功！']);
            }else{
                return json(['status' => 0, 'info' => '添加失败！']);
            }
        }

        $productCate = model('productcate') -> where(['uid' => session('userinfo:id')]) -> select();
        $this -> assign('productCate', $productCate);
        return view();
    }
    //编辑产品
    public function editproduct(){
        if($this -> request -> isPost()){
            $input = input('post.');
            $input['update_time'] = time();
            $input['content'] = preg_replace('/<script[^>]*?>.*?<\/script>/si','',$input['content']);
            $input['content'] = htmlspecialchars_decode($input['content']);
            $input['content'] = preg_replace("/<a[^>]*>(.*?)<.*?\/a.*?>/is", "$1", $input['content']);
            $updateResult = model('product') -> update($input);
            if($updateResult){
                return json(['status' => 1, 'info' => '更新成功！']);
            }else{
                return json(['status' => 0, 'info' => '更新失败！']);
            }
        }

        $id = input('id');
        $productCate = model('productcate') -> where(['uid' => session('userinfo:id')]) -> select();
        $oneproduct = model('product') -> where(['id' => $id]) -> find();

        $this -> assign('productCate', $productCate);
        $this -> assign('oneproduct', $oneproduct);
        return view();
    }
    //删除产品
    public function delproduct(){
        $id = input('id');
        $delResult = model('product') -> where(['id' => $id]) -> delete();
        if($delResult) {
            echo "<script>top.location.href='/admin/productcate/productindex?ref=addtabs'</script>";
        }else{
            echo "<script>alert('删除失败！');top.location.href='/admin/productcate/productindex?ref=addtabs'</script>";
        }
    }
    //批量删除产品
    public function delSelectInputProducts(){
        $input = input('post.');
        $inputid = json_decode($input['checkList'], true);
        $ids['id'] = implode(',', $inputid);
        $delResult = model('product') -> where(['id' => ['in', $ids['id']]]) -> delete();
        if($delResult){
            return json(['status' => 1, 'info' => '删除成功！']);
        }
        return json(['status' => 0, 'info' => '删除失败！']);
    }
    //七牛上传
    public function qiniu() {
        $file = $this -> request -> file('myfile');
        $filePath = $file -> getInfo('tmp_name');

        $ext = pathinfo($file -> getInfo('name'), PATHINFO_EXTENSION);
        $key = 'upload/'.date('Ymdhis').substr(md5($file -> getRealPath()), 0, 5). rand(0, 999).'.'.$ext;

        vendor('qiniu.autoload');
        $accessKey = config('ACCESSKEY');
        $secretKey = config('SECRETKEY');
        $auth = new \Qiniu\Auth($accessKey, $secretKey);
        $bucket = config('BUCKET');
        $domain = config('domain');
        // 生成上传Token
        $token = $auth->uploadToken($bucket);
        $uploaderMgr = new \Qiniu\Storage\UploadManager();
        //调用putFile方法上传文件
        list($ret, $err) = $uploaderMgr -> putFile($token, $key, $filePath);
        if($err !== null) {
            return json(['status' => 0, 'info' => $err]);
        }else {
            return json(['status' => 1, 'info' => '上传成功！', 'data' => '//'.$domain.'/'.$ret['key']]);
        }
    }
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

}
